package ar.uade.edu.fain.ad.client.web.util;

import java.rmi.RMISecurityManager;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import ar.uade.edu.fain.ad.client.delegate.DelegateFactory;
import ar.uade.edu.fain.ad.client.delegate.rmi.util.RMIDelegateFactory;

public class WebUtils {

	private static WebUtils instance;

	private DelegateFactory delegateFactory;
	
	private WebUtils() {
		super();
		initDelegateFactory();
	}

	private void initDelegateFactory() {
		final RMIDelegateFactory rmiDelegateFactory = new RMIDelegateFactory();
		try {
			final InitialContext context = new InitialContext();
			final String serverName = (String) 
					context.lookup("java:comp/env/server/name");
			final Integer serverPort = (Integer) 
					context.lookup("java:comp/env/server/port");
			rmiDelegateFactory.setServerName(serverName);
			rmiDelegateFactory.setServerPort(serverPort);
		} catch (NamingException e) {
			System.err.println(
					"ERROR: No se pudo levantar los datos de conectividad "
					+ "con el server desde el JNDI environment,"
					+ " usando defaults.");
			e.printStackTrace(System.err);
		}
		if (Boolean.getBoolean("enable.rmi.security")) {
			System.setSecurityManager(new RMISecurityManager());
		}
		this.delegateFactory = rmiDelegateFactory;
	}
	
	public DelegateFactory getDelegateFactory() {
		return delegateFactory;
	}

	public static WebUtils get() {
		if (instance == null) {
			instance = new WebUtils();
		}
		return instance;
	}

}
